package orange.database;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

//import org.apache.log4j.Logger;

/**
 * 数据库连接及释放 ，通过连接TOMCAT 连接池 获取数据库的缓冲，并对数据库进行回收处理。
 * 配置 web.xml 及CONTEXT.XML 来修改连接池的配置信息。
 * @version v1.0.0 beta
 */


public class DBIns {
	
//	private static Logger log = Logger.getLogger(DBIns.class) ;

	static DBIns instance = new DBIns();;

	public static DBIns getInstance() {
		if (instance == null)
			instance = new DBIns();
		return instance;
	}

	protected DBIns() {}

	private Connection getConnectionFromPool() {  
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:comp/env/database");// 必须要
			Connection con = ds.getConnection();
			return con;
		} catch (Exception e) {
//			log.error(e.getMessage() , e.fillInStackTrace()) ;
			e.printStackTrace();
		}
		// SQL.getInstance().release(con);
		// con.close();

		return null;
	}

	public Connection getConnection() {
		Connection conn = getConnectionFromPool();
		if (conn == null) {
			conn = getConnectionFromPool();
			if (conn == null)
				conn = getConnectionFromPool();
		}
		return conn;
	}

	public Connection getConnectionByActionName(String actionName) {
		return getConnection();
	}

	public boolean release(Connection conn) {
		if (conn != null) {
			try {
				conn.clearWarnings() ;
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
//				log.error(e.getMessage(),e.fillInStackTrace()) ;
				e.printStackTrace();
			}
			conn = null;
		}
		return true;
	}
	
	public void destory(){
		instance = null ;
//		log = null ;
	}
}
